

const http = require('http');
let html = `
    <!DOCTYPE html>
    <html>
        <head> 
            <title>First HTTP</title>
        </head>
        <body>
            你好
        </body>
    </html>
`
/*
    .jpg  .jepg->image/jepg
    .png->image/png
    .gif->image/x-icon
    .txt->text/plain
    .json->text/json 或 application/json
    .xml->text/xml 或 application/xml
*/ 

let routerTable = {
    '/':async (req,res)=>{
        res.setHeader('content-type','text/html;charset=utf-8')
        res.end(html)
    },
    '/test':async (req,res) =>{
        let status = parseInt(Math.random()*200)+199
        res.statusCode=status
        res.end('test end');
    },
    '/data': async (req,res)=>{
        let bufferList = [];
        let bufferLength = 0;
        request.on('data',chunk=>{
            bufferLength+=chunk.length;
            bufferList.push(chunk)
        })
        let bodyData=null;
        req.on('end',()=>{
            if(bufferList.length>8){
                bodyData=Buffer.concat(bufferList,bufferLength);
                bufferList=[];
            }
            if(bodyData){
                res.end(bodyData)
            }else{
                res.end();
            }
        })
    }
}

http.createServer((req,res)=>{
   if(!routerTable[req.url]){
        res.statusCode=404
        res.end('page not found')
        return
   }
   routerTable[req.url](req.res);
    
}).listen(3456);